package admin

import (
	"blog-server/models/views"
	"blog-server/service"
	"blog-server/utils/msg"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

type FileController struct {
	FileService *service.FileService
}

func NewFileController() *FileController {
	return &FileController{
		service.NewFileService(),
	}
}

// UploadFile 文件上传
func (file *FileController) UploadFile(c *gin.Context) {
	var fileUploadVo views.FileUploadVo
	if err := c.ShouldBind(&fileUploadVo); err != nil {
		c.JSON(http.StatusBadRequest, msg.NewMsg().Failed(err.Error()))
		return
	}
	model, err := file.FileService.Upload(fileUploadVo)
	if err != nil {
		c.JSON(http.StatusBadRequest, msg.NewMsg().Failed(err.Error()))
		return
	}
	c.JSON(http.StatusOK, model)
}

// DownloadFile 文件下载
func (file *FileController) DownloadFile(c *gin.Context) {
	query := c.Query("id")
	name, content, err := file.FileService.FileInfo(query)
	if err != nil {
		c.JSON(http.StatusBadRequest, msg.NewMsg().Success(err.Error()))
	} else {
		c.Writer.WriteHeader(http.StatusOK)
		c.Header("Content-Type", "application/.*")
		c.Header("Content-Disposition", "attachment; filename="+name)
		c.Header("Accept-Length", fmt.Sprintf("%d", len(content)))
		_, _ = c.Writer.Write(content)
	}
}

// FileList 文件列表
func (file *FileController) FileList(c *gin.Context) {
	var fileListVo views.FileListVo
	if err := c.ShouldBind(&fileListVo); err != nil {
		c.JSON(http.StatusBadRequest, msg.NewMsg().Failed(err.Error()))
		return
	}
}
